using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace PhpDocBlockGenerator.Model.Php
{
    /// <summary>
    /// class to check a php file for syntax errors with the help of php.exe
    /// </summary>
    public class PhpErrorCheck
    {
        /// <summary>
        /// the location of the File, that will be checked
        /// </summary>
        private String _file = String.Empty;
        public String File
        {
            get { return _file; }
            set { _file = value; }
        }

        /// <summary>
        /// the process to execute the php.exe
        /// </summary>
        private Process _checkProcess = new Process();

        /// <summary>
        /// the return of the php.exe after the filecheck
        /// </summary>
        public string Output { get; set; }

        /// <summary>
        /// the location of the PhpExe
        /// </summary>
        public string PhpExe { get; set; }


        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="phpExeFile">the location of the php.exe</param>
        /// <param name="file">the location of the file, which will be checked</param>
        public PhpErrorCheck(String phpExeFile, String file)
        {
            PhpExe = phpExeFile;
            File = file;
            _SetProcessValues();
            StartProcessAndGetReturn();
        }


        /// <summary>
        /// Checks if the Output is Valid or not
        /// </summary>
        /// <returns>true|false</returns>
        public Boolean IsValid()
        {
            MatchCollection regResult = PhpRegex.RegSearchPhpExeParseNoErrors.Matches(Output);

            if (regResult.Count > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// checks the file for syntax errors and saves the output state internally
        /// </summary>
        /// <returns></returns>
        public void StartProcessAndGetReturn()
        {
            _checkProcess.Start();
            _checkProcess.WaitForExit();
            if (_checkProcess.HasExited)
            {
                Output = _checkProcess.StandardOutput.ReadToEnd();
            }
        }


        /// <summary>
        /// Sets all values, which will be required to get the
        /// information
        /// </summary>
        private void _SetProcessValues()
        {
            _checkProcess.StartInfo.UseShellExecute = false;
            _checkProcess.StartInfo.RedirectStandardOutput = true;
            _checkProcess.StartInfo.CreateNoWindow = true;
            _checkProcess.StartInfo.FileName = PhpExe;
            _checkProcess.StartInfo.Arguments = "-l -f \"" + File + "\"";
        }
    }
}
